package com.kong.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kong.constant.MessageConstant;
import com.kong.constant.RedisConstant;
import com.kong.entity.Result;
import com.kong.pojo.Order;
import com.kong.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author yang2013
 * @data 2020/10/15 16:08
 */
@RestController
@RequestMapping("/order")
public class OrderMobileController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    /**
     * 另一种思路 直接return orderservice.submitOrder
     * 让service层直接返回result
     * @param map
     * @return
     */
    @PostMapping("/submit")
    public Result order(@RequestBody Map<String, Object> map){
        try {
            Jedis jedis = jedisPool.getResource();
            String telephone = (String) map.get("telephone");
            String key= RedisConstant.SENDTYPE_ORDER+"_"+telephone;
            String value = jedis.get(key);
            String code= (String) map.get("code");
            if (StringUtils.isEmpty(code)){
                return new Result(false, MessageConstant.VALIDATECODE_FAIL);
            }
            if (!code.equals(value)){
                return new Result(false,MessageConstant.VALIDATECODE_ERROR);
            }
            Order order=orderService.submitOrder(map);
            if (false){
                jedis.del(key);
            }
            //设置预约的类型
            map.put("orderType",MessageConstant.ORDER_TELEPHONE);
            return new Result(true,MessageConstant.ORDER_SUCCESS);
        }catch (RuntimeException r){
            return new Result(false,r.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDER_FAIL);
        }
    }


    /**
     * 体检预约成功页面数据查询
     */
    @GetMapping("/findById")
    public Result findByid(Integer id){
        try {
            Map<String, Object> map=orderService.findDetailById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS, map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
